const canvas = document.getElementById('tetrisCanvas');
const ctx = canvas.getContext('2d');
const blockSize = 20;
const rows = 20;
const cols = 10;
let board = [];
let currentPiece;
let score = 0;

// 初始化游戏板
function initBoard() {
    for (let r = 0; r < rows; r++) {
        board[r] = [];
        for (let c = 0; c < cols; c++) {
            board[r][c] = 0;
        }
    }
}

// 绘制游戏板
function drawBoard() {
    for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) {
            if (board[r][c]) {
                ctx.fillStyle = '#FF0000';
                ctx.fillRect(c * blockSize, r * blockSize, blockSize, blockSize);
            }
        }
    }
}

// 生成新方块
function newPiece() {
    const shapes = [
        [[1, 1], [1, 1]], // 方块O
        [[1, 1, 1, 1]], // 方块I
        [[1, 1], [0, 1], [0, 1]], // 方块L
        [[0, 1], [0, 1], [1, 1]], // 方块反L
        [[1, 1, 0], [0, 1, 1]], // 方块Z
        [[0, 1, 1], [1, 1, 0]], // 方块反Z
        [[1, 0], [1, 0], [1, 1]] // 方块T
    ];
    const randomShape = shapes[Math.floor(Math.random() * shapes.length)];
    currentPiece = {
        shape: randomShape,
        position: {x: Math.floor(cols / 2 - randomShape[0].length / 2), y: 0},
        rotation: 0
    };
}

function checkCollision(newPosition) {
    for (let r = 0; r < currentPiece.shape.length; r++) {
        for (let c = 0; c < currentPiece.shape[r].length; c++) {
            if (currentPiece.shape[r][c]) {
                const newX = currentPiece.position.x + c;
                const newY = currentPiece.position.y + r;
                if (newX < 0 || newX >= cols || newY >= rows || board[newY][newX]) {
                    return true; // 碰撞发生
                }
            }
        }
    }
    return false; // 无碰撞
}

function clearLines() {
    let linesCleared = 0;
    outer: for (let r = rows - 1; r >= 0; r--) {
        for (let c = 0; c < cols; c++) {
            if (!board[r][c]) {
                continue outer;
            }
        }
        // 行满，清除该行
        board.splice(r, 1);
        board.unshift(new Array(cols).fill(0));
        linesCleared++;
    }
    if (linesCleared) {
        score += linesCleared * 100; // 假设每消除一行得100分
        document.getElementById('score').innerText = score;
    }
}

// 绘制当前方块
function drawPiece(ctx, currentPiece, blockSize, offset) {
    // offset 是画布上方块起始位置的偏移量，例如，可能是画布顶部留出的行数
    const { position, shape } = currentPiece;

    // 设置方块的颜色或其他样式
    ctx.fillStyle = '#0099FF'; // 例如，蓝色

    // 遍历方块形状中的每个单元格
    for (let y = 0; y < shape.length; y++) {
        for (let x = 0; x < shape[y].length; x++) {
            if (shape[y][x]) { // 如果该位置有方块（通常用1表示）
                // 计算在画布上的实际坐标
                const drawX = (position.x + x) * blockSize + offset.x;
                const drawY = (position.y + y) * blockSize + offset.y;

                // 在计算出的坐标上绘制一个矩形（即方块的一个单元）
                ctx.fillRect(drawX, drawY, blockSize, blockSize);
            }
        }
    }
}

// 更新游戏状态
function update() {
    if (!checkCollision({x: currentPiece.position.x, y: currentPiece.position.y + 1})) {
        currentPiece.position.y++; // 方块下落
    } else {
        // 方块触底，锁定并生成新方块
        for (let r = 0; r < currentPiece.shape.length; r++) {
            for (let c = 0; c < currentPiece.shape[r].length; c++) {
                if (currentPiece.shape[r][c]) {
                    board[currentPiece.position.y + r][currentPiece.position.x + c] = 1;
                }
            }
        }
        clearLines();
        newPiece();
        if (checkCollision(currentPiece.position)) {
            // 如果新生成的方块立即碰撞，游戏结束
            alert("游戏结束!");
            // clearInterval(gameLoopInterval); // 停止游戏循环
        }
    }
}

// 控制方块移动
document.addEventListener('keydown', (e) => {
    switch (e.keyCode) {
        case 37: // 左箭头键
            // 判断左移是否会导致碰撞
            if (!checkCollision({x: currentPiece.position.x - 1, y: currentPiece.position.y})) {
                currentPiece.position.x--;
            }
            break;
        case 39: // 右箭头键
            // 判断右移是否会导致碰撞
            if (!checkCollision({x: currentPiece.position.x + 1, y: currentPiece.position.y})) {
                currentPiece.position.x++;
            }
            break;
        case 40: // 下箭头键
            // 快速下降，直接下移一行
            while (!checkCollision({x: currentPiece.position.x, y: currentPiece.position.y + 1})) {
                currentPiece.position.y++;
            }
            break;
        case 38: // 上箭头键 或 ' '（空格键）通常用于旋转
            // 旋转方块前需要先判断旋转后是否会碰撞
            const rotatedShape = rotate(currentPiece.shape);
            if (!checkCollision({x: currentPiece.position.x, y: currentPiece.position.y}, rotatedShape)) {
                currentPiece.shape = rotatedShape;
            }
            break;
        // 可以添加更多控制，比如使用 'A' 和 'D' 键作为替代的左右移动键等
    }
});

// 添加一个旋转方块的辅助函数
function rotate(shape) {
    const N = shape.length;
    const result = [];
    for (let i = 0; i < N; i++) {
        result[i] = [];
        for (let j = 0; j < N; j++) {
            result[i][j] = shape[N - 1 - j][i];
        }
    }
    return result;
}


// 游戏主循环
function gameLoop() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawBoard();
    drawPiece();
    update();
    requestAnimationFrame(gameLoop);
}
function startGame() {
    document.getElementById('startButton').disabled = true;
    initBoard();
    newPiece();
    gameLoop();
}
